$(function(){

 	var ajaxManager = new AjaxManager();
	var renderer = new Renderer();
	var customerId = $("#hidden_customer_id").val();
	/*一开始隐藏地址*/
	$(".shade_content").hide();
	$(".shade").hide();

	var span_momey = $(".span_momey");
	var b = 0;
	for (var i = 0; i < span_momey.length; i++) {
		b += parseFloat($(span_momey[i]).html());
	}
	var out_momey = $(".out_momey");


	initReceiverInfo();


	function initReceiverInfo(){
		ajaxManager.findByCustomerId(customerId, renderer.renderSelect);
	}
	// 定义数据结构
	 // 购物车里面的条目： OrderItem
    function OrderItem(){
        var id;
        var total;
        var name;
        var price;
        var img;
        var merchantName;
        var subTotalMoney;
    };
    
    //定义收货信息
    function ReceiverInfo(){
    	var id;
		var address;
		var name;
		var phone;
	};	


	function AjaxManager(){
		var obj = {};
		
		obj.addAddress = function(json,onSuccess){
			$.ajax({
					type:"POST",
					url:"receiverInfo",
					data:json,
					contentType:"application/json",
					dataType: "json"
				
			}).done(function(msg){
				onSuccess(msg);
				if(msg != null){
					alert("添加成功。");
				}
			});
		};


		obj.add = function(receiverInfoJson){
			$.ajax({
				type: "POST",
				url: "orderInfo",
				data: receiverInfoJson,
				contentType:"application/json"
			}).done(function(){
				window.location="home";
			})
		};

		obj.findByCustomerId = function(customerId, onSuccess){
			$.ajax({
				type:"GET",
				url: "receiverInfo/customerId/"+customerId,
				dataType: "json"
			}).done(function(receiverInfos){
				onSuccess(receiverInfos);
			})
		};

		 obj.delItemFromCart = function(foodId, onSuccess){
            $.ajax({
                url: 'orderItems/'+foodId,
                type:"DELETE",
                dataType: "json"
            }).done(function(items){
                //window.location=
            });
        }

         // 点击了购物车中的 + 按钮
        obj.plusOneItemToCart = function(foodId){
            $.ajax({
                url: "orderItems/"+foodId,
                type: "PATCH",
            }).done(function(items){
                // onSuccess(items);
            });
        };
		

		// 点击了购物车中的 - 按钮
        obj.minusOneItemToCart = function(foodId){
            $.ajax({
                url: "orderItems/foodId/"+foodId,
                type: "DELETE",
              
            }).done(function(items){
                // onSuccess(items);
            });
        }
		return obj;
	}

	function Renderer(){
		var obj = {};
		obj.renderSelect = function(data){
			var select = $("#sel");
			select.empty();
			$.each(data, function(index, addressVO){
				var html = "<option id="+addressVO.id +">" + addressVO.name + '    ' + addressVO.phone + '   ' + addressVO.address +"</option>";
				select.append($.parseHTML(html));
			});
		};
		
		return obj;
	}
					
	$("#sub_setID").on("click",function(){
		 var add = new ReceiverInfo();
		
		add.address =  $("#address").val();
		add.phone = $("#phone").val();
		add.name = $("#name_").val();
		ajaxManager.addAddress(JSON.stringify(add),renderer.renderSelect);
		
		$(".shade_content").hide();
		$(".shade").hide();
	});
	
	$(".btn_remove").on("click", function(){
		$(".shade_content").hide();
		$(".shade").hide();
	})



    /*各种监听器*/
    function onclick_btnAdd(a) {
		var sib = $("#orderItemVO_value_name").parent().siblings().eq(2);
		var out_momey = $(".out_momey");
		var input_ = $(a).prev();
		var input_val = $(a).prev().val();
		var input_add = parseInt(input_val) + 1;
		input_.val(input_add);
		var btn_momey = parseFloat($(a).parent().prev().children().html());
		var out_momey_float = parseFloat(out_momey.html()) + btn_momey;
		out_momey.text(out_momey_float.toFixed(2));
	};


	/*隐藏添加地址栏*/
	// $(".shade_content").hide();

	$('.nav_mini ul li').hover(function() {
			$(this).find('.two_nav').show(100);
		}, function() {
			$(this).find('.two_nav').hide(100);
		});

	$('.left_nav').hover(function() {
			$(this).find('.nav_mini').show(100);
		}, function() {
			$(this).find('.nav_mini').hide(100);
		})

	/*关闭地址新增按钮*/
	$("#button_to_close_address_info").on("click", function(){
		var shade_content = $(".shade_content");
		var shade = $(".shade");
		if (confirm("确认关闭么！此操作不可恢复")) {
			shade_content.hide();
			shade.hide();
		}
	});

	/*弹出新增地址按钮*/
	$("#use_new_address_btn").on("click", function(){
		$(".shade_content").show();
		$(".shade").show();
		var input_out = $(".input_style");
		for (var i = 0; i <= input_out.length; i++) {
			if ($(input_out[i]).val() != "") {
				$(input_out[i]).val("");
			}
		}
	});

	/*点击了 + 号*/
	$(".btn_add").on("click", function(event){
		var out_momey = $(".out_momey");
		var input_ = $(event.target).prev();
		var input_val = $(event.target).prev().val();
		var input_add = parseInt(input_val) + 1;
		input_.val(input_add);
		var btn_momey = parseFloat($(event.target).parent().prev().children().html());
		var out_momey_float = parseFloat(out_momey.html()) + btn_momey;

		var foodId = $(event.target).parent().prev().prev().children().eq(0).attr("id");
		ajaxManager.plusOneItemToCart(foodId);
		out_momey.text(out_momey_float.toFixed(2));
	});

	/*点击了 - 号*/
	$(".btn_reduce").on("click", function(event){
		var out_momey = $(".out_momey");
		var input_ = $(event.target).next();
		var input_val = $(event.target).next().val();
		if (input_val <= 0) {
			alert("商品个数不能小于0！")
		} else {
			var input_add = parseInt(input_val) - 1;
			input_.val(input_add);
			var btn_momey = parseFloat($(event.target).parent().prev().children().html());
			var out_momey_float = parseFloat(out_momey.html()) - btn_momey;
			out_momey.text(out_momey_float.toFixed(2));
			var foodId = $(event.target).parent().prev().prev().children().eq(0).attr("id");
			ajaxManager.minusOneItemToCart(foodId);

		}
	});

	$(".btn_r").on("click", function(event){
		 if (confirm("确认删除么！此操作不可恢复")) {
			var out_momey = $(".out_momey");
			var input_val = $(event.target).parent().prev().children().eq(1).val(); /* 数量 */
			var span_html = $(event.target).parent().prev().prev().children().html();  /*价格*/
			var out_add = parseFloat(input_val).toFixed(2) * parseFloat(span_html).toFixed(2); /*subTotalMoney*/
			var reduce = parseFloat(out_momey.html()).toFixed(2)- parseFloat(out_add).toFixed(2);
			//尝试获取 foodId
			var foodId = $(event.target).parent().prev().prev().prev().children().eq(0).attr("id");
			
			console.log(parseFloat(reduce).toFixed(2));
			out_momey.text(parseFloat(reduce).toFixed(2))
			$(event.target).parent().parent().remove();
			ajaxManager.delItemFromCart(foodId);
		 }
	})








	// $("#remove_food_in_orderInfo").on("click", function(event){
	// 	 if (confirm("确认删除么！此操作不可恢复")) {
	// 		var out_momey = $(".out_momey");
	// 		var input_val = $(event.target).parent().prev().children().eq(1).val(); /* 数量 */
	// 		var span_html = $(event.target).parent().prev().prev().children().html();  /*价格*/
	// 		var out_add = parseFloat(input_val).toFixed(2) * parseFloat(span_html).toFixed(2); /*subTotalMoney*/
	// 		var reduce = parseFloat(out_momey.html()).toFixed(2)- parseFloat(out_add).toFixed(2);
	// 		//尝试获取 foodId
	// 		var foodId = $(event.target).parent().prev().prev().prev().children().eq(0).attr("id");
			
	// 		// alert(out_momey+" "+input_val+" "+span_html+" "+out_add+" "+reduce+" "+"foodId "+foodId);

	// 		console.log(parseFloat(reduce).toFixed(2));
	// 		out_momey.text(parseFloat(reduce).toFixed(2))
	// 		$(event.target).parent().parent().remove();
	// 	 }
	// });


	$("#pay_from_orderInfo").on("click", function(event){
		var receiverInfo = new ReceiverInfo();
		var selSize = $("#sel option").size();
		if(selSize == 0){
			alert("请添加收货地址信息");
		}else{
			var receiverInfoId = $("#sel option:selected").attr("id");
			receiverInfo.id = receiverInfoId;
			receiverInfo.address = "";
			receiverInfo.phone = "";
			receiverInfo.name = "";
			ajaxManager.add(JSON.stringify(receiverInfo));
		}
	
	});

});